package com.itzhoun.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzhoun.constants.ScheduleConstants;
import com.itzhoun.entity.SysJob;
import com.itzhoun.exception.TaskException;
import com.itzhoun.mapper.JobMapper;
import com.itzhoun.service.JobService;
import com.itzhoun.utils.ScheduleUtils;
import org.quartz.JobDataMap;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author 周楠
 * @Date 2022/08/16/下午 11:03
 */
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, SysJob> implements JobService {

    @Resource
    private Scheduler scheduler;

    @Resource
    private JobMapper jobMapper;

    /**
     * 新增定时任务
     *
     * @param sysJob
     * @return
     */
    @Override
    public Boolean insertJob(SysJob sysJob) {
        sysJob.setCreateBy("itZhoun");
        sysJob.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        boolean save = this.save(sysJob);
        if (save) {
            try {
                ScheduleUtils.createScheduleJob(scheduler, sysJob);
            } catch (TaskException | SchedulerException tx) {
                tx.printStackTrace();
            }
        }
        return save;
    }

    @Override
    public void run(SysJob job) {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, job);
        try {
            scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量删除任务
     * @param jobIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByIds(Long[] jobIds) {
        for (Long jobId : jobIds) {
            deleteJobById(jobId);
        }
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param jobId 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteJobById(Long jobId) {
        SysJob sysJob = this.getById(jobId);
        try {
            int rows = jobMapper.deleteById(jobId);
            if (rows > 0) {
                scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, sysJob.getJobGroup()));
            }
            return rows > 0;
        } catch (SchedulerException s) {
            s.printStackTrace();
        }
        return false;
    }

    /**
     * 修改状态
     *
     * @param job
     * @return
     */
    @Override
    public Boolean changeStatus(SysJob job) {
        String status = job.getStatus();
        try {
            if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
                return resumeJob(job);
            } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
                return pauseJob(job);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 停止任务
     *
     * @param job 调度信息
     * @return
     * @throws SchedulerException
     */
    @Override
    public Boolean pauseJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.updateById(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows > 0;
    }

    /**
     * 恢复任务
     *
     * @param job
     * @return
     * @throws SchedulerException
     */
    @Override
    public Boolean resumeJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = jobMapper.updateById(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows > 0;
    }
}
